<template>
  <div class="addQuestion">
    <div class="container">
      <div class="addQuestionHeader">
        <div class="addQuestionHeaderLeft">
          <h2 v-if="!currentId">新增题目</h2>
          <h2 v-if="currentId">修改题目</h2>
        </div>

        <div class="addQuestionHeaderRight">
          <el-button
            class="backBtn"
            @click="back"
          >返回</el-button>
        </div>

      </div>

      <div class="addQuestionForm">
        <el-form
          :model="addQuestionForm"
          label-width="auto"
          :rules="rules"
          ref="addForm"
        >
          <el-form-item
            label="题目名称:"
            prop="topic"
          >
            <div style="display: flex; justify-content: space-between;">
              <el-input
                v-model="addQuestionForm.topic"
                style="width: 800px;height: 36px;"
              />
              <el-tag
                closable
                type="warning"
                style="height: 40px;;margin-left: 24px; background-color: #EEEEEE;font-size: 16px;color: #F99D38;overflow: hidden;"
                v-if="imgFileName.topicImage[0]?.name"
                @close="closeTag('topicImage')"
              >{{ imgFileName.topicImage[0]?.name.substring(0,30) }}</el-tag>

              
              <AssmentUpload
                style="margin-left: 24px"
                v-model:fileList="imgFileName.topicImage"
                :limit="100"
                :showFileList="false"
              >
                <template #empty>
                  <el-button
                    class="universalBtn"
                    style="height: 40px;"
                  >选择图片</el-button>
                </template>
              </AssmentUpload>

            </div>

          </el-form-item>

          <el-form-item label="题目分类:">
            <el-select
              multiple
              v-model="topicClassification"
              collapse-tags-tooltip
              collapse-tags
              :max-collapse-tags="6"
              style="width: 800px;height: 36px;"
            >
              <el-option
                v-for="item in questionTypeList"
                :key="item.id"
                :value="item.id"
                :label="item.classify"
              >

              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="题目类型:"
            prop="topicType"
          >
            <el-radio-group
              class="ml-4"
              v-model="addQuestionForm.topicType"
              @change="questionTypeChange"
            >
              <!-- :disabled="currentId" -->
              <el-radio
                size="large"
                :label="0"
              >单选题</el-radio>
              <el-radio
                size="large"
                :label="1"
              >多选题</el-radio>
              <el-radio
                size="large"
                :label="2"
              >判断题</el-radio>
              <el-radio
                size="large"
                :label="3"
              >填空题</el-radio>
              <el-radio
                size="large"
                :label="4"
              >论述题</el-radio>
            </el-radio-group>

          </el-form-item>
          <el-form-item
            label="选项数量:"
            v-if="questionType == '1'"
          >
            <el-select
              v-model="addQuestionForm.optionNumber"
              style="width: 800px;height: 45px;"
            >
              <el-option :value="4">4</el-option>
              <el-option :value="5">5</el-option>
              <el-option :value="6">6</el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="选项A:"
            prop="optionA"
            v-if="questionType == '0' || questionType == '1' || questionType == '2'"
          >
            <div style="display: flex; justify-content: space-between;">
              <el-input
                v-model="addQuestionForm.optionA"
                style="width: 800px;height: 36px;"
              />
              <el-tag
                type="warning"
                v-if="imgFileName.optionA[0]?.name"
                closable
                style="height: 40px;margin-left: 24px; background-color: #EEEEEE;font-size: 16px;color: #F99D38;overflow: hidden;"
                @close="closeTag('optionA')"
              >{{ imgFileName.optionA[0]?.name.substring(0,30) }}</el-tag>
              <AssmentUpload
                style="margin-left: 24px;"
                v-model:fileList="imgFileName.optionA"
                :limit="100"
                :showFileList="false"
              >
                <template #empty>

                  <el-button
                    class="universalBtn"
                    style="height: 40px"
                  >选择图片</el-button>
                </template>
              </AssmentUpload>
            </div>
          </el-form-item>

          <el-form-item
            label="选项B:"
            prop="optionB"
            v-if="questionType == '0' || questionType == '1' || questionType == '2'"
          >
            <div style="display: flex; justify-content: space-between;">
              <el-input
                v-model="addQuestionForm.optionB"
                style="width: 800px;height: 36px;"
              />
              <el-tag
                type="warning"
                v-if="imgFileName.optionB[0]?.name"
                closable
                style="height: 40px;margin-left: 24px; background-color: #EEEEEE;font-size: 16px;color: #F99D38;"
                @close="closeTag('optionB')"
              >{{ imgFileName.optionB[0]?.name.substring(0,30) }}</el-tag>
              <AssmentUpload
                style="margin-left: 24px;"
                v-model:fileList="imgFileName.optionB"
                :limit="100"
                :showFileList="false"
              >
                <template #empty>
                  <el-button
                    class="universalBtn"
                    style="height: 40px;"
                  >选择图片</el-button>
                </template>
              </AssmentUpload>
            </div>

          </el-form-item>
          <el-form-item
            label="选项C:"
            prop="optionC"
            v-if="questionType == '0' || questionType == '1'"
          >
            <div style="display: flex; justify-content: space-between;">
              <el-input
                v-model="addQuestionForm.optionC"
                style="width: 800px;height: 36px;"
              />
              <el-tag
                type="warning"
                v-if="imgFileName.optionC[0]?.name"
                closable
                style="height: 40px;margin-left: 24px;background-color: #EEEEEE;font-size: 16px;color: #F99D38;"
                @close="closeTag('optionC')"
              >{{ imgFileName.optionC[0]?.name.substring(0,30) }}</el-tag>
              <AssmentUpload
                style="margin-left: 24px;"
                v-model:fileList="imgFileName.optionC"
                :limit="100"
                :showFileList="false"
              >
                <template #empty>
                  <el-button
                    class="universalBtn"
                    style="height: 40px"
                  >选择图片</el-button>
                </template>
              </AssmentUpload>

            </div>

          </el-form-item>
          <el-form-item
            label="选项D:"
            prop="optionD"
            v-if="questionType == '0' || questionType == '1'"
          >
            <div style="display: flex; justify-content: space-between;">
              <el-input
                v-model="addQuestionForm.optionD"
                style="width: 800px;height: 36px;"
              />
              <el-tag
                type="warning"
                v-if="imgFileName.optionD[0]?.name"
                closable
                style="height: 40px;margin-left: 24px;background-color: #EEEEEE;font-size: 16px;color: #F99D38;"
                @close="closeTag('optionD')"
              >
                {{ imgFileName.optionD[0]?.name.substring(0,30) }}
              </el-tag>
              <AssmentUpload
                style="margin-left: 24px;"
                v-model:fileList="imgFileName.optionD"
                :limit="100"
                :showFileList="false"
              >
                <template #empty>
                  <el-button
                    class="universalBtn"
                    style="height: 40px"
                  >选择图片</el-button>
                </template>
              </AssmentUpload>

            </div>

          </el-form-item>

          <el-form-item
            label="选项E:"
            v-if="questionType == '1' && addQuestionForm.optionNumber >= 5"
          >
            <div style="display: flex; justify-content: space-between;">
              <el-input
                v-model="addQuestionForm.optionE"
                style="width: 800px;height: 36px;"
              />
              <el-tag
                v-if="imgFileName.optionE[0]?.name"
                type="warning"
                closable
                style="height: 40px;margin-left: 24px;background-color: #EEEEEE;font-size: 16px;color: #F99D38;"
                @close="closeTag('optionE')"
              >{{ imgFileName.optionE[0]?.name.substring(0,30) }}</el-tag>
              <AssmentUpload
                style="margin-left: 24px;"
                v-model:fileList="imgFileName.optionE"
                :limit="100"
                :showFileList="false"
              >
                <template #empty>
                  <el-button
                    class="universalBtn"
                    style="height: 40px;"
                  >选择图片</el-button>
                </template>
              </AssmentUpload>

            </div>

          </el-form-item>
          <el-form-item
            label="选项F:"
            v-if="questionType == '1' && addQuestionForm.optionNumber >= 6"
          >
            <div style="display: flex; justify-content: space-between;">
              <el-input
                v-model="addQuestionForm.optionF"
                style="width: 800px;height: 36px;"
              />
              <el-tag
                v-if="imgFileName.optionF[0]?.name"
                type="warning"
                closable
                style="height: 40px;margin-left: 24px;background-color: #EEEEEE;font-size: 16px;color: #F99D38;"
                @close="closeTag('optionF')"
              >{{ imgFileName.optionF[0]?.name.substring(0,30) }}</el-tag>

              <AssmentUpload
                style="margin-left: 24px;"
                v-model:fileList="imgFileName.optionF"
                :limit="100"
                :showFileList="false"
              >
                <template #empty>
                  <el-button
                    class="universalBtn"
                    style="height: 40px"
                  >选择图片</el-button>
                </template>
              </AssmentUpload>

            </div>

          </el-form-item>

          <el-form-item
            label="正确答案:"
            prop="rightAnswers"
            v-if="questionType == '0' || questionType == '2'"
          >
            <el-radio-group
              class="ml-4"
              v-model="addQuestionForm.rightAnswers"
            >
              <el-radio
                size="large"
                label="A"
              >选项A</el-radio>
              <el-radio
                size="large"
                label="B"
              >选项B</el-radio>
              <el-radio
                size="large"
                label="C"
                v-if="questionType == '0' || questionType == '1'"
              >选项C</el-radio>
              <el-radio
                size="large"
                label="D"
                v-if="questionType == '0' || questionType == '1'"
              >选项D</el-radio>
              <el-radio
                size="large"
                label="E"
                v-if="questionType == '1' && addQuestionForm.optionNumber >= 5"
              >选项E</el-radio>
              <el-radio
                size="large"
                label="F"
                v-if="questionType == '1' && addQuestionForm.optionNumber >= 6"
              >选项F</el-radio>
            </el-radio-group>

          </el-form-item>
          <el-form-item
            label="正确答案:"
            v-if="questionType == '1'"
            prop="rightAnswersMore"
          >
            <el-checkbox-group
              class="ml-4"
              v-model="rightAnswersMore"
            >
              <el-checkbox
                size="large"
                label="A"
              >选项A</el-checkbox>
              <el-checkbox
                size="large"
                label="B"
              >选项B</el-checkbox>
              <el-checkbox
                size="large"
                label="C"
                v-if="questionType == '0' || questionType == '1'"
              >选项C</el-checkbox>
              <el-checkbox
                size="large"
                label="D"
                v-if="questionType == '0' || questionType == '1'"
              >选项D</el-checkbox>
              <el-checkbox
                size="large"
                label="E"
                v-if="(questionType == '1' && addQuestionForm.optionNumber >= 5) && addQuestionForm.optionE != ''"
              >选项E</el-checkbox>
              <el-checkbox
                size="large"
                label="F"
                v-if="(questionType == '1' && addQuestionForm.optionNumber >= 6) && addQuestionForm.optionF != ''"
              >选项F</el-checkbox>
            </el-checkbox-group>

          </el-form-item>
          <el-form-item
            label="正确答案:"
            prop="rightAnswers"
            v-if="questionType == '3' || questionType == '4'"
          >
            <el-input
              type="textarea"
              v-model="addQuestionForm.rightAnswers"
              :rows="3"
              style="width: 800px"
            />
          </el-form-item>
          <el-form-item label="答案解析:">
            <el-input
              type="textarea"
              v-model="addQuestionForm.analysis"
              :rows="3"
              style="width: 800px"
            />
          </el-form-item>

        </el-form>

        <div class="btnBox">
          <el-button
            class="cancelBtn"
            @click="cancelBtn"
          >取消</el-button>
          <el-button
            class="saveBtn"
            @click="saveBtn"
          >保存</el-button>
          <Fileupload
            :limit="1"
            :file-type="['jpg', 'png']"
            :isShowTip="false"
          ></Fileupload>
        </div>
      </div>
    </div>

  </div>

</template>

<script setup>
import { ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router'
import AssmentUpload from '@/views/assment/AssmentUpload'

// 引入新增题目，查询题目分类,查询题目信息，修改题目的接口
import { addQuestion, getQuestionType, getQuestionList, updateQuestion } from '@/api/assessment/questionmanage'

import { ElMessage } from 'element-plus'



const route = useRoute()
const router = useRouter()

// 引入文件上传的组件

const imgFileName = ref({
  topicImage: [],
  optionA: [],
  optionB: [],
  optionC: [],
  optionD: [],
  optionE: [],
  optionF: [],

})

// 标签关闭时的方法
function closeTag (imgType) {
  imgFileName.value[imgType] = []
}

const imgUrl = computed(() => {
  return {
    topicImage: imgFileName.value.topicImage[0]?.url,
    imageA: imgFileName.value.optionA[0]?.url,
    imageB: imgFileName.value.optionB[0]?.url,
    imageC: imgFileName.value.optionC[0]?.url,
    imageD: imgFileName.value.optionD[0]?.url,
    imageE: imgFileName.value.optionE[0]?.url,
    imageF: imgFileName.value.optionF[0]?.url,
  }
})

// 默认新增题目类型
const defaultType = computed(() => Number(route.query.type))

// 编辑时当前的id（路由参数）
const currentId = computed(() => route.query.id)

// 当前的操作类型
const operateType = computed(() => route.query.operateType)

// 当前数据页码
const pageNum = computed(() => route.query.pageNum)

// 获取题目分类的列表
const questionTypeList = ref([])
// 获取题目分类
async function getQuestionTypeList () {
  const res = await getQuestionType({ sourceType: 0 })
  // console.log(res)
  questionTypeList.value = res.rows
}
getQuestionTypeList()

// 多选框数据（需置空）
const rightAnswersMore = ref([])
const rightAnswersMore1 = computed(() => {
  if (rightAnswersMore.value) {
    return rightAnswersMore.value.join(',')
  }
})
// 题目分类多选（需置空）
const topicClassification = ref([])
const topicClassification1 = computed(() => topicClassification.value.join(','))
const addQuestionForm = ref({
  topic: '', // 题目名称
  topicClassification: topicClassification1,
  topicType: defaultType.value, // 题目分类
  optionA: "",
  optionB: "",
  optionC: "",
  optionD: "",
  optionE: "",
  optionF: "",
  analysis: "",
  rightAnswers: '',
  rightAnswersMore: rightAnswersMore1,
  optionNumber: 4, // 选项数量
  sourceType: 0
})

const rules = ref({
  topic: [
    { required: true, message: '请输入题目名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  topicType: [
    { required: true, message: '请选择题目分类', trigger: 'change' }
  ],
  optionA: [
    { required: true, message: '请输入选项A', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  optionB: [
    { required: true, message: '请输入选项B', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  optionC: [
    { required: true, message: '请输入选项C', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  optionD: [
    { required: true, message: '请输入选项D', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  rightAnswers: [
    { required: true, message: '请选择正确答案', trigger: 'change' }
  ],
  rightAnswersMore: [
    { required: true, message: '请选择正确答案', trigger: 'change' },
    { min: 1, max: 500, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
})

const questionType = computed(() => Number(addQuestionForm.value.topicType))



// 定义回显信息
const questionInfo = ref({})
// 编辑时信息回显
async function getQuestionInfo () {
  if (currentId.value) {
    const res = await getQuestionList({ id: currentId.value, sourceType: 0 })
    console.log(res)
    questionInfo.value = res.rows[0]
    addQuestionForm.value = res.rows[0]
    topicClassification.value = res.rows[0].classifyInfo.map(item => item.id)

    console.log(questionTypeList.value)
    console.log(topicClassification.value)
    rightAnswersMore.value = res.rows[0].rightAnswersMore ? res.rows[0].rightAnswersMore.split(',') : ""
    if (questionInfo.value.topicImage !== null) {
      imgFileName.value.topicImage[0] = { name: questionInfo.value.topicImage }
    }
    if (questionInfo.value.imageA !== null) {
      imgFileName.value.optionA[0] = { name: questionInfo.value.imageA }
    }
    if (questionInfo.value.imageB !== null) {
      imgFileName.value.optionB[0] = { name: questionInfo.value.imageB }
    }
    if (questionInfo.value.imageC !== null) {
      imgFileName.value.optionC[0] = { name: questionInfo.value.imageC }
    }
    if (questionInfo.value.imageD !== null) {
      imgFileName.value.optionD[0] = { name: questionInfo.value.imageD }
    }
    if (questionInfo.value.imageE !== null) {
      imgFileName.value.optionE[0] = { name: questionInfo.value.imageE }
    }
    if (questionInfo.value.imageF !== null) {
      imgFileName.value.optionF[0] = { name: questionInfo.value.imageF }
    }

    let optionNumber = 0

    if (questionInfo.value.optionA != "") {
      optionNumber++
    }
    if (questionInfo.value.optionB !== "") {
      optionNumber++
    }
    if (questionInfo.value.optionC !== "") {
      optionNumber++
    }
    if (questionInfo.value.optionD !== "") {
      optionNumber++
    }
    if (questionInfo.value.optionE !== "") {
      optionNumber++
    }
    if (questionInfo.value.optionF !== "") {
      optionNumber++
    }

    addQuestionForm.value.optionNumber = optionNumber

  }
}
getQuestionInfo()

// 当题型发生变化的时候，清空表单下方内容
function questionTypeChange (item) {
  // console.log(123)
  // console.log(item)
  if (item == 0 || item == 2 || item == 3 || item == 4) {
    imgFileName.value.optionA = []
    imgFileName.value.optionB = []
    imgFileName.value.optionC = []
    imgFileName.value.optionD = []
    imgFileName.value.optionE = []
    imgFileName.value.optionF = []
    rightAnswersMore.value = []
    addQuestionForm.value.optionA = ""
    addQuestionForm.value.optionB = ""
    addQuestionForm.value.optionC = ""
    addQuestionForm.value.optionD = ""
    addQuestionForm.value.optionE = ""
    addQuestionForm.value.optionF = ""
    addQuestionForm.value.rightAnswers = ""
    // addQuestionForm.value.rightAnswersMore = ""
  } else if (item == 1) {
    imgFileName.value.optionA = []
    imgFileName.value.optionB = []
    imgFileName.value.optionC = []
    imgFileName.value.optionD = []
    imgFileName.value.optionE = []
    imgFileName.value.optionF = []
    rightAnswersMore.value = []
    addQuestionForm.value.optionA = ""
    addQuestionForm.value.optionB = ""
    addQuestionForm.value.optionC = ""
    addQuestionForm.value.optionD = ""
    addQuestionForm.value.optionE = ""
    addQuestionForm.value.optionF = ""
    addQuestionForm.value.rightAnswers = ""
    // addQuestionForm.value.rightAnswersMore = ""
    addQuestionForm.value.optionNumber = 4
  }

}



const addForm = ref(null)
// 保存按钮的方法
async function saveBtn () {
  // console.log(imgFileName)
  // 确定新增题目
  await addForm.value.validate(async (valid) => {
    let count = countUppercaseLetters(rightAnswersMore1.value)
    if (addQuestionForm.value.topicType == 1 && count < 2) {
      return ElMessage({
        message: "多选题答案最少有两个选项，请检查",
        type: "error"
      })
    }
    if (valid) {
      if (operateType.value === 'edit') {
        await updateQuestion(
          {
            topicType: questionType.value,
            ...addQuestionForm.value,
            ...imgUrl.value
          }
        )
        ElMessage({
          message: "修改题目成功！",
          type: "success"
        })
      } else {
        const res = await addQuestion([{
          topicType: questionType.value,
          ...addQuestionForm.value,
          ...imgUrl.value
        }])
        ElMessage({
          message: "新增题目成功！",
          type: "success"
        })
      }


      cancelBtn()
    }
  })
}
function countUppercaseLetters (str) {
  if (str) {
    let count = 0;
    for (let i = 0; i < str.length; i++) {
      const charCode = str.charCodeAt(i);
      // 检查字符是否在大写字母的Unicode范围内 (A-Z 的ASCII码范围是65-90)  
      if (charCode >= 65 && charCode <= 90) {
        count++;
      }
    }
    return count;
  }
}
// 处理返回的方法
function back () {
  cancelBtn()
}

function handleSuccess (file) {
  imgFileName.value.chooseQuestion = file
}

function cancelBtn () {
  router.push({
    path: 'questionbank',
    query: {
      pageNum: pageNum.value,
      activeIndex: Number(JSON.parse(localStorage.getItem('activeIndex1')))
    }
  })
  imgFileName.value = {
    topicImage: [],
    optionA: [],
    optionB: [],
    optionC: [],
    optionD: [],
    optionE: [],
    optionF: [],
  }
  addQuestionForm.value = {
    topic: '', // 题目名称
    topicClassification: "",
    topicType: null, // 题目分类
    optionA: "",
    optionB: "",
    optionC: "",
    optionD: "",
    optionE: "",
    optionF: "",
    analysis: "",
    rightAnswers: '',
    rightAnswersMore: '',
    optionNumber: 4, // 选项数量
    sourcetype: 0
  }
  rightAnswersMore1.value = []
  topicClassification.value = []

}




</script>

<style lang="scss" scoped>
.addQuestion {
  padding: 32px 32px 0 32px;
  background: #f5f6f9;
  .container {
    min-height: 1036px;
    border-radius: 10px;
    background: #ffffff;
  }

  .addQuestionHeader {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 88px;
    padding: 0 32px;
    border-bottom: 1px solid #d4d4d4;

    .addQuestionHeaderRight {
      .backBtn {
        width: 80px;
        height: 40px;
        border-radius: 6px 6px 6px 6px;
        border: 1px solid #5974ff;
        font-size: 16px;
        color: #5974ff;
        &:hover {
          background-color: transparent;
        }
        &:focus {
          background-color: transparent;
        }
      }
    }
  }

  .addQuestionForm {
    padding: 40px 193px 0 191px;
  }

  ::v-deep(.el-radio__inner) {
    border-radius: 0;
  }

  ::v-deep(.el-radio.el-radio--large) {
    margin-right: 54px;
  }

  .btnBox {
    margin-top: 88px;

    .cancelBtn {
      width: 108px;
      height: 40px;
      border-radius: 6px 6px 6px 6px;
      border: 1px solid #5974ff;
      font-size: 16px;
      color: #5974ff;
      &:hover {
        background-color: transparent;
      }
      &:focus {
        background-color: transparent;
      }
    }

    .saveBtn {
      width: 108px;
      height: 40px;
      background: #5974ff;
      border-radius: 6px 6px 6px 6px;
      font-size: 16px;
      color: #ffffff;
    }
  }

  .universalBtn {
    width: 108px;
    height: 40px;
    border-radius: 6px 6px 6px 6px;
    border: 1px solid #5974ff;
    font-size: 16px;
    color: #5974ff;
    &:focus {
      background-color: transparent;
    }
    &:hover {
      background-color: transparent;
    }
  }
}
::v-deep(.el-upload--picture-card) {
  border: none;
  --el-upload-picture-card-size: none;
}

::v-deep(.el-select-tags-wrapper) {
  // margin-top: 25px;
}
</style>